import MarkdownIt from 'markdown-it';
import DOMPurify from 'dompurify';
import hljs from 'highlight.js';

// Configure markdown-it instance with safe defaults
const md = new MarkdownIt({
    html: false, // disallow raw HTML from AI output
    linkify: true,
    breaks: true,
    highlight(code: string, language?: string) {
        try {
            if (language && hljs.getLanguage(language)) {
                const highlighted = hljs.highlight(code, { language, ignoreIllegals: true }).value;
                return `<pre><code class="hljs language-${language}">${highlighted}</code></pre>`;
            }
        } catch (err) {
            // fallthrough to escaped block below
        }
        const escaped = md.utils.escapeHtml(code);
        return `<pre><code class="hljs">${escaped}</code></pre>`;
    },
});

export function renderAiMarkdown(content: string | undefined | null): string {
    const text = content ?? '';
    const html = md.render(text);
    return DOMPurify.sanitize(html);
}